package com.ww.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by admin on 2017/9/12.
 */
public class BaseDao<T> {
    @Autowired
    protected SessionFactory sessionFactory;

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    protected Class<T> persistentClass;

    protected Class getTrueType(Class cls) {
        Type type = cls.getGenericSuperclass();
        Class trueCls = null;

        if (type instanceof ParameterizedType) {
            Type temp = ((ParameterizedType) type).getActualTypeArguments()[0];
            if (temp instanceof Class)
                trueCls = (Class) temp;
        }

        return trueCls;
    }

    public BaseDao() {
        persistentClass = getTrueType(getClass());
    }


    public T getById(String id) {
        return getSession().get(persistentClass, id);
    }


    public void save(T obj) {
        getSession().save(obj);
    }

    public void update(T obj) {
        getSession().update(obj);
    }

    public void delete(T obj) {
        getSession().delete(obj);
    }
}
